<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="入库单编号" prop="recptCode">
        <el-input v-model="queryParams.recptCode" placeholder="请输入入库单编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="入库单名称" prop="recptName">
        <el-input v-model="queryParams.recptName" placeholder="请输入入库单名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="供应商名称" prop="vendorName">
        <el-input v-model="queryParams.vendorName" placeholder="请输入供应商名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="订单编号" prop="poCode">
        <el-input v-model="queryParams.poCode" placeholder="请输入订单编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="入库日期" prop="recptDate">
        <el-date-picker clearable v-model="queryParams.recptDate" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择入库日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['mes:wm:itemrecpt:edit']">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="itemrecptList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="入库单编号" align="center" width="180px" prop="recptCode">
        <template slot-scope="scope">
          <el-button type="text" @click="handleView(scope.row)"
            v-hasPermi="['mes:wm:itemrecpt:list']">{{ scope.row.recptCode }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="入库单名称" align="center" prop="recptName" :show-overflow-tooltip="true" />
      <el-table-column label="供应商名称" align="center" prop="vendorName" :show-overflow-tooltip="true" />
      <el-table-column label="入库日期" align="center" prop="recptDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.recptDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="采购订单号" align="center" prop="poCode" />
      <el-table-column label="批次号" align="center" prop="batchNoList" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.batchNoList ? scope.row.batchNoList.join(',') : ''"
            placement="top">
            <span>{{ scope.row.batchNoList ? scope.row.batchNoList.join(',') : '' }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="单据状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_order_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-video-play" v-if="scope.row.status == 'PREPARE'"
            @click="handleExecute(scope.row)" v-hasPermi="['mes:wm:itemrecpt:edit']">执行入库</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" v-if="scope.row.status == 'PREPARE'"
            @click="handleUpdate(scope.row)" v-hasPermi="['mes:wm:itemrecpt:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" v-if="scope.row.status == 'PREPARE'"
            @click="handleDelete(scope.row)" v-hasPermi="['mes:wm:itemrecpt:edit']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 添加或修改物料入库单对话框 -->
    <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="入库单编号" prop="recptCode">
              <el-input v-model="form.recptCode" :disabled="form.recptId ? true : false" placeholder="系统自动生成" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label-width="80">
              <el-switch :disabled="form.recptCode != null" v-model="autoGenFlag" active-color="#13ce66"
                active-text="自动生成" @change="handleAutoGenChange(autoGenFlag)"
                v-if="optType != 'view' && form.status == 'PREPARE'">
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库单名称" prop="recptName">
              <el-input v-model="form.recptName" placeholder="请输入入库单名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="入库日期" prop="recptDate">
              <el-date-picker clearable v-model="form.recptDate" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择入库日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="采购订单号" prop="poCode">
              <el-select v-model="form.poCode" placeholder="请选择采购订单号" @change="onPoCodeChange">
                <el-option v-for="dict in poCodeOptions" :key="dict.poCode" :label="dict.poCode"
                  :value="dict.poCode"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单据状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择单据状态" :disabled="true">
                <el-option label="草稿" value="PREPARE" />
                <el-option label="已确认" value="CONFIRMED" />
                <el-option label="已入库" value="COMPLETED" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="供应商" prop="vendorName">
              <el-input v-model="form.vendorName" readonly="readonly" placeholder="请选择供应商">
                <el-button slot="append" @click="handleSelectVendor" icon="el-icon-search"></el-button>
              </el-input>
              <VendorSelect ref="vendorSelect" v-if="showItemSelect" @closeSelect="closeSelect"
                @onSelected="onVendorSelected" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入库仓库" prop="warehouseId" required>
              <el-select v-model="form.warehouseId" placeholder="请选择入库仓库" @change="handleWarehouseChange">
                <el-option v-for="item in warehouseOptions" :key="item.pId" :label="item.pName" :value="item.pId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 修改时 -->
      <el-divider content-position="center">物料信息</el-divider>
      <el-card shadow="always" class="box-card">
        <div v-if="form.recptId" class="po-tip">
          <el-alert title="修改模式下，可以调整实际入库数量、仓库的库区库位等信息" type="success" :closable="false" show-icon>
          </el-alert>
        </div>
        <Itemrecptline ref="line" :recptId="form.recptId" :poCode="form.poCode" :warehouseId="form.warehouseId"
          :locationId="form.locationId" :areaId="form.areaId" :optType="optType"
          :purchaseOrderData="getCurrentPurchaseOrderData()" :backendData="getBackendData()"
          @updateTotalPrice="updateTotalPrice" @updateLineFields="updateLineFields">
        </Itemrecptline>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancel" v-if="optType == 'view' || form.status != 'PREPARE'">返回</el-button>
        <el-button type="primary" @click="submitForm" v-if="form.status == 'PREPARE' && optType != 'view'">保
          存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listItemrecpt, getItemrecpt, delItemrecpt, addItemrecpt, updateItemrecpt, confirmItemrecpt, execute } from "@/api/mes/wm/itemrecpt";
import { getTreeList } from "@/api/mes/wm/warehouse"
import { genCode } from "@/api/system/autocode/rule"
import { listPurchaseOrder, getPurchaseOrderDetail } from "@/api/mes/pro/purchaseOrder";
// 供应商弹框组件
import VendorSelect from "@/components/vendorSelect/single.vue";
// 检验单编号
import IqcSelect from "@/components/iqcSelect/single.vue";
import Itemrecptline from "./line.vue";
export default {
  name: "Itemrecpt",
  dicts: ['mes_order_status'],
  components: { VendorSelect, IqcSelect, Itemrecptline },
  data() {
    return {
      // 自动生成编码
      autoGenFlag: false,
      optType: undefined,
      warehouseInfo: [],
      warehouseOptions: [],
      warehouseProps: {
        multiple: false,
        value: 'pId',
        label: 'pName',
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物料入库单表格数据
      itemrecptList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        recptCode: null,
        recptName: null,
        iqcId: null,
        iqcCode: null,
        vendorId: null,
        vendorCode: null,
        vendorName: null,
        vendorNick: null,
        warehouseId: null,
        warehouseCode: null,
        warehouseName: null,
        locationId: null,
        locationCode: null,
        locationName: null,
        areaId: null,
        areaCode: null,
        areaName: null,
        recptDate: null,
        poCode: null,
        status: null,
      },
      // 表单参数 - 新增时不设置默认值，让用户手动输入
      form: {
        recptId: null,
        recptCode: null,
        recptName: null,
        iqcId: null,
        iqcCode: null,
        vendorId: null,
        vendorCode: null,
        vendorName: null,
        vendorNick: null,
        warehouseId: null,
        warehouseCode: null,
        warehouseName: null,
        locationId: null,
        locationCode: null,
        locationName: null,
        areaId: null,
        areaCode: null,
        areaName: null,
        recptDate: null,
        poCode: null,
        poId: null,
        status: "PREPARE",
        remark: null,
        totalTaxIncl: "0.00",
        totalTaxExcl: "0.00",
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        userId: null,
        params: {},
        searchValue: null
      },
      // 表单校验
      rules: {
        recptCode: [
          { required: true, message: "入库单编号不能为空", trigger: "blur" }
        ],
        recptName: [
          { required: true, message: "入库单名称不能为空", trigger: "blur" }
        ],
        recptDate: [
          { required: true, message: "入库时间不能为空", trigger: "blur" }
        ],
        vendorName: [
          { required: true, message: "请选择对应的供应商", trigger: "blur" }
        ],
        warehouseId: [
          { required: true, message: "请选择入库仓库", trigger: "change" }
        ]
      },
      poCodeOptions: [], // 采购订单
      showItemSelect: true, // 是否显示供应商选择组件
      showIqcSelect: true, // 是否显示IQC选择组件
      currentBatchCode: null // 当前批次号
    };
  },
  created() {
    this.getList();
    this.getWarehouseList();
    this.getPurchaseOrderList();
    // 初始化当前用户信息
    this.initUserInfo();
  },
  methods: {
    // 初始化用户信息
    initUserInfo() {
      const userInfo = this.$store.state.user;
      if (userInfo) {
        this.form.createBy = userInfo.name;
        this.form.updateBy = userInfo.name;
        this.form.userId = userInfo.id;
      }
    },
    /** 获取已确认的采购订单列表 */
    getPurchaseOrderList() {
      listPurchaseOrder({
        pageNum: 1,
        pageSize: 9999,
        status: 'CONFIRMED'
      }).then(res => {
        if (res.rows && res.rows.length > 0) {
          this.poCodeOptions = res.rows;
        } else {
          this.poCodeOptions = [];
          this.$message.warning('暂无可用的已确认采购订单');
        }
      }).catch(error => {
        console.error('获取采购订单列表失败:', error);
        this.$message.error('获取采购订单列表失败');
        this.poCodeOptions = [];
      });
    },
    // 确保当前单据的采购订单号出现在下拉选项中
    ensurePoOption(poCode, vendorInfo = {}) {
      if (!poCode) return;
      const exists = this.poCodeOptions && this.poCodeOptions.find(item => item.poCode === poCode);
      if (!exists) {
        const extra = {
          poCode,
          id: vendorInfo.poId || null,
          vendorId: vendorInfo.vendorId || null,
          vendorCode: vendorInfo.vendorCode || null,
          vendorName: vendorInfo.vendorName || null,
        };
        this.poCodeOptions = [extra, ...(this.poCodeOptions || [])];
      }
    },
    /** 查询物料入库单列表 */
    getList() {
      this.loading = true;
      listItemrecpt(this.queryParams).then(response => {
        this.itemrecptList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getWarehouseList() {
      getTreeList().then(response => {
        if (response.data) {
          this.warehouseOptions = response.data.filter(el => {
            return el.warehouseCode.indexOf('VIR') === -1;
          });
          // 处理仓库数据结构，补充编码信息
          this.warehouseOptions.forEach(w => {
            w.warehouseCode = w.pCode; // 假设pCode对应仓库编码
            w.children.forEach(l => {
              l.locationCode = l.lCode; // 假设lCode对应库位编码
              l.children.forEach(a => {
                a.areaCode = a.aCode; // 假设aCode对应库区编码
              });
            });
          });
        }
        let ostr = JSON.stringify(this.warehouseOptions).replace(/warehouseId/g, 'pId').replace(/warehouseName/g, 'pName');
        this.warehouseOptions = JSON.parse(ostr);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        recptId: null,
        recptCode: null,
        recptName: null,
        iqcId: null,
        iqcCode: null,
        vendorId: null,
        vendorCode: null,
        vendorName: null,
        vendorNick: null,
        warehouseId: null,
        warehouseCode: null,
        warehouseName: null,
        locationId: null,
        locationCode: null,
        locationName: null,
        areaId: null,
        areaCode: null,
        areaName: null,
        recptDate: null,
        poCode: null,
        poId: null,
        status: "PREPARE",
        remark: null,
        totalTaxIncl: "0.00",
        totalTaxExcl: "0.00",
        createBy: this.$store?.state?.user?.name || 'admin',
        createTime: this.formatDateTime(new Date()),
        updateBy: this.$store?.state?.user?.name || 'admin',
        updateTime: this.formatDateTime(new Date()),
        userId: null,
        params: {},
        searchValue: null
      };
      this.autoGenFlag = false;
      this.currentBatchCode = null;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.recptId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.warehouseInfo = [];
      this.open = true;
      this.title = "添加物料入库单";
      this.optType = "add";
      // 新增时自动生成入库单编号
      this.autoGenFlag = true;
      this.handleAutoGenChange(true);
      // 新增时只设置必要的默认值，其他字段保持为空让用户输入
      this.form.recptDate = this.formatDate(new Date());
      this.form.status = "PREPARE";
    },
    // 查询明细按钮操作
    handleView(row) {
      this.reset();
      const recptIds = row.recptId
      getItemrecpt(recptIds).then(response => {
        this.form = { ...response.data, params: response.data.params || {} };
        this.ensurePoOption(this.form.poCode, {
          vendorId: this.form.vendorId,
          vendorCode: this.form.vendorCode,
          vendorName: this.form.vendorName,
          poId: this.form.poId
        });
        this.warehouseInfo[0] = response.data.warehouseId;
        this.warehouseInfo[1] = response.data.locationId;
        this.warehouseInfo[2] = response.data.areaId;
        this.open = true;
        this.title = "查看入库单信息";
        this.optType = "view";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const recptId = row.recptId || this.ids
      getItemrecpt(recptId).then(response => {
        this.form = { ...response.data, params: response.data.params || {} };
        this.ensurePoOption(this.form.poCode, {
          vendorId: this.form.vendorId,
          vendorCode: this.form.vendorCode,
          vendorName: this.form.vendorName,
          poId: this.form.poId
        });
        this.warehouseInfo[0] = response.data.warehouseId;
        this.warehouseInfo[1] = response.data.locationId;
        this.warehouseInfo[2] = response.data.areaId;
        this.open = true;
        this.title = "修改物料入库单";
        this.optType = "edit";
      });
    },
    // 执行入库
    handleExecute(row) {
      const recptIds = row.recptId || this.ids;
      this.$modal.confirm('确认执行入库？').then(function () {
        return execute(recptIds)
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("入库成功");
      }).catch(() => { });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 补充采购订单ID
          if (this.form.poCode) {
            const selectedPo = this.poCodeOptions.find(item => item.poCode === this.form.poCode);
            if (selectedPo) {
              this.form.poId = selectedPo.id;
            }
          }
          // 获取子组件的行数据
          let lineList = [];
          if (this.$refs.line) {
            lineList = [...this.$refs.line.itemrecptlineList];
          }
          console.log(this.$refs.line._data,'lineList')
          // 预处理表单数据，确保所有字段都不为null
          const processedForm = this.preprocessFormData(this.form);
          console.log(processedForm,'processedForm')
          // 构建完整的提交数据结构
          const submitData = {
            itemRecpt: processedForm,
            lineList: lineList.map(line => {
              // 预处理行数据，确保所有字段都不为null
              const processedLine = this.preprocessLineData(line);
              return {
                ...processedLine,
                recptId: processedForm.recptId,
                warehouseId: processedForm.warehouseId,
                warehouseCode: processedForm.warehouseCode,
                warehouseName: processedForm.warehouseName,
                locationId: processedForm.locationId,
                locationCode: processedForm.locationCode,
                locationName: processedForm.locationName,
                areaId: processedForm.areaId,
                areaCode: processedForm.areaCode,
                areaName: processedForm.areaName,
                createBy: processedForm.createBy,
                updateBy: processedForm.updateBy,
                userId: processedForm.userId
              };
            })
          };
          if (this.form.recptId != null) {
            updateItemrecpt(submitData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            console.log(submitData);
            addItemrecpt(submitData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 预处理表单数据，确保所有字段都不为null
    preprocessFormData(formData) {
      const processed = { ...formData };
      
      // 移除不需要的字段
      delete processed.totalTaxIncl;
      delete processed.totalTaxExcl;
      
      // 为字符串字段设置默认值
      const stringFields = [
        'areaCode', 'areaName', 'createBy', 'iqcCode', 'locationCode', 'locationName',
        'poCode', 'recptCode', 'recptName', 'remark', 'searchValue', 'status',
        'updateBy', 'vendorCode', 'vendorName', 'vendorNick', 'warehouseCode', 'warehouseName'
      ];
      stringFields.forEach(field => {
        if (!processed[field] || processed[field] === null || processed[field] === undefined) {
          if (field === 'status') {
            processed[field] = 'PREPARE';
          } else if (field === 'createBy' || field === 'updateBy') {
            processed[field] = this.$store.state.user?.name || 'admin';
          } else if (field === 'recptCode') {
            // 入库单编号由用户输入或自动生成，不设置随机默认值
            processed[field] = processed[field] || '';
          } else if (field === 'recptName') {
            // 入库单名称由用户输入，不设置随机默认值
            processed[field] = processed[field] || '';
          } else {
            // 其他字段不设置随机默认值，保持为空字符串
            processed[field] = processed[field] || '';
          }
        }
      });
      // 为数字字段设置默认值
      const numberFields = [
        'areaId', 'iqcId', 'locationId', 'poId', 'recptId', 'userId', 'vendorId', 'warehouseId'
      ];
      numberFields.forEach(field => {
        if (!processed[field] || processed[field] === null || processed[field] === undefined) {
          if (field === 'recptId') {
            processed[field] = processed[field] || 0; // 新增时保持为0
          }else if (field === 'iqcId') {
            processed[field] = processed[field] || 0; // 新增时保持为0
          } else {
            // 其他数字字段不设置随机默认值，保持为0
            processed[field] = processed[field] || 0;
          }
        }
      });
      // 为日期字段设置默认值
      const dateFields = ['createTime', 'updateTime', 'recptDate']
      dateFields.forEach(field => {
        if (!processed[field] || processed[field] === null || processed[field] === undefined) {
          if (field === 'recptDate') {
            processed[field] = this.formatDate(new Date());
          } else {
            // 确保时间字段使用完整的日期时间格式
            const currentDate = new Date();
            processed[field] = this.formatDateTime(currentDate);
            console.log(`设置 ${field} 为: ${processed[field]}`);
          }
        } else if (processed[field] && typeof processed[field] === 'string') {
          // 如果已经是字符串，使用验证函数检查和修正格式
          if (field === 'createTime' || field === 'updateTime') {
            processed[field] = this.validateAndFixDateTime(processed[field], field);
          }
        }
      });
      // 为对象字段设置默认值
      if (!processed.params || processed.params === null) {
        processed.params = {};
      }
      return processed;
    },
    // 预处理行数据，确保所有字段都不为null
    preprocessLineData(lineData) {
      const processed = { ...lineData };
      
      // 移除不需要的字段
      delete processed.attr1;
      delete processed.attr2;
      delete processed.attr3;
      delete processed.attr4;
      delete processed.warehouseInfo;
      delete processed.tempId;
      
      // 为字符串字段设置默认值
      const stringFields = [
        'areaCode', 'areaName', 'batchCode', 'bizUser', 'createBy', 'currency',
        'gift', 'iqcCheck', 'iqcCode', 'itemCode', 'itemName', 'locationCode', 'locationName',
        'remark', 'searchValue', 'specification', 'unitOfMeasure', 'updateBy',
        'warehouseCode', 'warehouseName'
      ];
      stringFields.forEach(field => {
        if (!processed[field] || processed[field] === null || processed[field] === undefined) {
          if (field === 'iqcCheck') {
            processed[field] = 'N';
          } else if (field === 'currency') {
            processed[field] = 'CNY';
          } else if (field === 'unitOfMeasure') {
            processed[field] = 'PCS';
          } else if (field === 'createBy' || field === 'updateBy') {
            processed[field] = this.$store.state.user?.name || 'admin';
          } else if (field === 'itemCode') {
            // 物料编码由用户输入或选择，不设置随机默认值
            processed[field] = processed[field] || '';
          } else if (field === 'itemName') {
            // 物料名称由用户输入或选择，不设置随机默认值
            processed[field] = processed[field] || '';
          } else {
            // 其他字段不设置随机默认值，保持为空字符串
            processed[field] = processed[field] || '';
          }
        }
      });
      // 为数字字段设置默认值
      const numberFields = [
        'amount', 'amountTotal', 'areaId', 'discount', 'exchRate', 'invoiceAmount',
        'iqcId', 'itemId', 'lineId', 'locationId', 'price', 'priceExTax',
        'quantityArrive', 'quantityBegin', 'quantityOrder', 'quantityRecived',
        'quantityTotal', 'recptId', 'totalPrice', 'totalPriceExTax', 'userId', 'warehouseId'
      ];
      numberFields.forEach(field => {
        if (!processed[field] || processed[field] === null || processed[field] === undefined) {
          if (field === 'lineId') {
            processed[field] = processed[field] || 0;
          } else if (field === 'recptId') {
            processed[field] = processed[field] || 0;
          } else if (field === 'areaId') {
            processed[field] = processed[field] || 0;
          } else if (field === 'quantityRecived') {
            processed[field] = processed[field] || 0;
          } else if (field === 'price' || field === 'priceExTax') {
            processed[field] = processed[field] || 0;
          } else if (field === 'discount') {
            processed[field] = processed[field] || 1;
          } else if (field === 'exchRate') {
            processed[field] = processed[field] || 1;
          } else {
            processed[field] = processed[field] || 0;
          }
        }
      });
      // 为日期字段设置默认值
      const dateFields = ['createTime', 'updateTime', 'expireDate'];
      dateFields.forEach(field => {
        if (!processed[field] || processed[field] === null || processed[field] === undefined) {
          if (field === 'expireDate') {
            // 设置过期日期为一年后
            const expireDate = new Date();
            expireDate.setFullYear(expireDate.getFullYear() + 1);
            processed[field] = this.formatDate(expireDate);
          } else {
            // 确保时间字段使用完整的日期时间格式
            const currentDate = new Date();
            processed[field] = this.formatDateTime(currentDate);
            console.log(`设置 ${field} 为: ${processed[field]}`);
          }
        } else if (processed[field] && typeof processed[field] === 'string') {
          // 如果已经是字符串，使用验证函数检查和修正格式
          if (field === 'createTime' || field === 'updateTime') {
            processed[field] = this.validateAndFixDateTime(processed[field], field);
          }
        }
      });
      // 为对象字段设置默认值
      if (!processed.params || processed.params === null) {
        processed.params = {};
      }
      return processed;
    },
    doconfirm() {
      let that = this;
      this.$modal.confirm('是否完成入库单编制？【完成后将不能更改】').then(function () {
        that.form.status = 'CONFIRMED';
        that.submitForm();
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const recptIds = row.recptId || this.ids;
      this.$modal.confirm('是否确认删除物料入库单？').then(function () {
        return delItemrecpt(recptIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      // 调用导出的接口将文件进行导出
      this.download('mes/wm/itemrecpt/export', {
        ...this.queryParams
      }, `itemrecpt_${new Date().getTime()}.xlsx`)
    },
    // 选择默认的仓库、库区、库位
    handleWarehouseChanged(obj) {
      if (obj != null) {
        this.form.warehouseId = obj[0];
        this.form.locationId = obj[1];
        this.form.areaId = obj[2];
      }
    },
    // IQC检验单选择
    handleSelectIqc() {
      this.$refs.iqcSelect.showFlag = true;
    },
    // IQC检验单选择弹出框回调
    onIqcSelected(obj) {
      if (obj != undefined && obj != null) {
        this.form.iqcId = obj.iqcId;
        this.form.iqcCode = obj.iqcCode;
        if (!this.form.recptName) {
          this.form.recptName = obj.iqcName;
        }
        this.form.vendorId = obj.vendorId;
        this.form.vendorCode = obj.vendorCode;
        this.form.vendorName = obj.vendorName;
        this.form.vendorNick = obj.vendorNick;
      }
    },
    // 供应商选择
    handleSelectVendor() {
      this.$refs.vendorSelect.showFlag = true;
    },
    // 供应商选择弹出框回调
    onVendorSelected(obj) {
      if (obj != undefined && obj != null) {
        this.form.vendorId = obj.vendorId;
        this.form.vendorCode = obj.vendorCode;
        this.form.vendorName = obj.vendorName;
        this.form.vendorNick = obj.vendorNick;
        this.closeSelect();
      }
    },
    // 自动生成编码
    handleAutoGenChange(autoGenFlag) {
      if (autoGenFlag) {
        genCode('ITEMRECPT_CODE').then(response => {
          this.form.recptCode = response;
        });
      } else {
        this.form.recptCode = null;
      }
    },
    // 这里是关闭供应商选择方法
    closeSelect() {
      this.showItemSelect = false;
      setTimeout(() => {
        this.showItemSelect = true;
      }, 200)
    },
    // 在methods中添加采购订单号变化处理方法
    handlePoCodeChange(poCode) {
      // 判断poCOde是否为假值
      if (!poCode) {
        this.clearPoDetails();
        return;
      }
      // 静默获取采购订单详情，失败时不显示错误提示
      this.getPoDetailsSilently(poCode);
    },
    // 静默获取采购订单详情，失败时直接清空数据
    async getPoDetailsSilently(poCode) {
      try {
        this.loading = true;
        const response = await getPurchaseOrderDetail(poCode);
        if (response && response.data) {
          // 成功获取数据，填充表单
          this.handlePoDetailsSuccess(response.data);
        } else {
          // 数据为空，直接清空
          this.clearPoDetails();
        }
      } catch (error) {
        console.log('采购订单不存在或获取失败，静默处理');
        // 静默失败，直接清空数据，不显示任何错误提示
        this.clearPoDetails();
      } finally {
        this.loading = false;
      }
    },
    // 清空采购订单相关数据
    clearPoDetails() {
      // 清空供应商信息
      this.form.vendorId = null;
      this.form.vendorCode = null;
      this.form.vendorName = null;
      this.form.vendorNick = null;
      // 清空采购订单ID
      this.form.poId = null;
    },
    // 处理采购订单详情成功
    handlePoDetailsSuccess(data) {
      // 填充供应商信息
      if (data.vendor) {
        this.form.vendorId = data.vendor.vendorId;
        this.form.vendorCode = data.vendor.vendorCode;
        this.form.vendorName = data.vendor.vendorName;
        this.form.vendorNick = data.vendor.vendorNick;
      }
      // 填充采购订单ID
      this.form.poId = data.poId;
      // 只有在物料选择为空的时候才会选择，否则就是需要去进行条件判断的
      if (this.$refs.line && (!this.$refs.line.itemrecptlineList || this.$refs.line.itemrecptlineList.length === 0)) {
        if (data.lineList && data.lineList.length > 0) {
          this.fillMaterialLines(data.lineList);
        }
      } else {
        console.log('物料行项目已存在，跳过自动填充');
      }
    },
    // 填充物料行项目
    fillMaterialLines(lineList) {
      if (this.$refs.line) {
        // 转换数据格式并填充到子组件
        const materialLines = lineList.map(line => ({
          itemId: line.itemId,
          itemCode: line.itemCode,
          itemName: line.itemName,
          specification: line.specification,
          unitOfMeasure: line.unitOfMeasure,
          quantityOrder: line.quantityOrder,
          quantityArrive: line.quantityArrive,
          price: line.price,
          // 其他必要字段...
        }));
        this.$refs.line.itemrecptlineList = materialLines;
      }
    },
    // 关闭IQC选择框
    closeIqcSelect() {
      this.showIqcSelect = false;
      setTimeout(() => {
        this.showIqcSelect = true;
      }, 200)
    },

    // 采购订单变更时，自动获取物料信息
    async onPoCodeChange(val) {
      if (val) {
        this.ensurePoOption(val, {
          vendorId: this.form.vendorId,
          vendorCode: this.form.vendorCode,
          vendorName: this.form.vendorName,
          poId: this.form.poId
        });

        const selectedPo = this.poCodeOptions.find(item => item.poCode === val);
        if (!selectedPo) {
          this.form.poCode = null;
          return;
        }

        this.form.poId = selectedPo.id;

        // 自动填充供应商信息
        if (selectedPo.vendorName) {
          this.form.vendorName = selectedPo.vendorName;
          this.form.vendorId = selectedPo.vendorId;
          this.form.vendorCode = selectedPo.vendorCode;
          this.form.vendorNick = selectedPo.vendorNick || '';
        }
        // 获取采购订单详情，填充物料信息
        try {
          const poDetail = await getPurchaseOrderDetail(val);
          if (poDetail && poDetail.items && poDetail.items.length > 0) {
            this.$nextTick(() => {
              if (this.$refs.line) {
                this.$refs.line.initLineList(poDetail.items);
              }
            });
          }
        } catch (error) {
          console.error('获取采购订单详情失败:', error);
          // this.$message.error('获取采购订单详情失败，请重试');
        }
      } else {
        // 清空供应商信息
        this.form.vendorName = '';
        this.form.vendorId = null;
        this.form.vendorCode = null;
        this.form.vendorNick = '';
        // 清空物料信息
        if (this.$refs.line) {
          this.$refs.line.resetLinelist();
        }
      }
    },
    // 仓库变更时，自动获取库区、库位
    handleWarehouseChange(val) {
      if (!val) return;

      // 查找选中的仓库信息
      const selectedWarehouse = this.warehouseOptions.find(w => w.pId === val);
      if (selectedWarehouse) {
        this.form.warehouseCode = selectedWarehouse.warehouseCode;
        this.form.warehouseName = selectedWarehouse.pName;

        // 自动选择第一个库位和库区
        if (selectedWarehouse.children && selectedWarehouse.children.length > 0) {
          const firstLocation = selectedWarehouse.children[0];
          this.form.locationId = firstLocation.pId;
          this.form.locationCode = firstLocation.locationCode;
          this.form.locationName = firstLocation.pName;
          if (firstLocation.children && firstLocation.children.length > 0) {
            const firstArea = firstLocation.children[0];
            this.form.areaId = firstArea.pId;
            this.form.areaCode = firstArea.areaCode;
            this.form.areaName = firstArea.pName;
          }
        }
      }
    },
    // 生成批次号
    generateBatchCode() {
      genCode('BATCH_CODE').then(response => {
        this.currentBatchCode = response;
        if (this.$refs.line) {
          this.$refs.line.setBatchCode(response);
        }
        this.$message.success(`批次号已生成: ${response}`);
      }).catch(error => {
        console.error('生成批次号失败:', error);
        this.$message.error('生成批次号失败，请重试');
      });
    },
    // 更新总价
    updateTotalPrice(totalData) {
      this.form.totalTaxIncl = totalData.totalTaxIncl;
      this.form.totalTaxExcl = totalData.totalTaxExcl;
    },
    // 接收子组件字段更新
    updateLineFields(fields) {
      // 可以在这里处理子组件传递的字段更新
      console.log('Received line fields update:', fields);
    },
    // 获取当前采购订单数据
    getCurrentPurchaseOrderData() {
      if (this.form.poCode && this.poCodeOptions) {
        const currentPo = this.poCodeOptions.find(item => item.poCode === this.form.poCode);
        if (currentPo) {
          return currentPo;
        }
      }
      return null;
    },
    // 获取后端数据
    getBackendData() {
      // 如果有入库单ID，尝试从后端获取数据
      if (this.form.recptId) {
        // 这里可以调用后端接口获取数据
        // 暂时返回表单数据作为后端数据
        return {
          recptId: this.form.recptId,
          poCode: this.form.poCode,
          warehouseId: this.form.warehouseId,
          locationId: this.form.locationId,
          areaId: this.form.areaId,
          batchNo: this.currentBatchCode,
          status: this.form.status,
          remark: this.form.remark,
          totalTaxIncl: this.form.totalTaxIncl,
          totalTaxExcl: this.form.totalTaxExcl,
          createBy: this.form.createBy,
          createTime: this.form.createTime ? this.validateAndFixDateTime(this.form.createTime, 'createTime') : this.formatDateTime(new Date()),
          updateBy: this.form.updateBy,
          updateTime: this.form.updateTime ? this.validateAndFixDateTime(this.form.updateTime, 'updateTime') : this.formatDateTime(new Date()),
          userId: this.form.userId,
          params: this.form.params
        };
      }
      // 如果没有入库单ID，返回空数组
      return [];
    },
    // 日期格式化方法
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    // 日期时间格式化方法
    formatDateTime(date) {
      if (!date || !(date instanceof Date)) {
        date = new Date();
      }
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    // 验证并修正日期时间格式
    validateAndFixDateTime(dateString, fieldName) {
      if (!dateString || typeof dateString !== 'string') {
        return this.formatDateTime(new Date());
      }
      // 检查是否已经是正确的格式 yyyy-MM-dd HH:mm:ss
      if (dateString.match(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/)) {
        return dateString;
      }
      // 检查是否是 yyyy-MM-dd HH:mm 格式，缺少秒数
      if (dateString.match(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/)) {
        const fixedDate = dateString + ':00';
        console.log(`修正 ${fieldName} 格式从 "${dateString}" 到 "${fixedDate}"`);
        return fixedDate;
      }
      // 检查是否是 yyyy-MM-dd 格式，缺少时间
      if (dateString.match(/^\d{4}-\d{2}-\d{2}$/)) {
        const fixedDate = dateString + ' 00:00:00';
        console.log(`修正 ${fieldName} 格式从 "${dateString}" 到 "${fixedDate}"`);
        return fixedDate;
      }
      // 如果格式不正确，返回当前时间
      console.warn(`日期格式不正确 "${dateString}"，使用当前时间`);
      return this.formatDateTime(new Date());
    }
  }
};
</script>
<style scoped>
.collapse-title {
  flex: 0 1 54%;
  order: 1;
}

.po-tip {
  margin-bottom: 15px;
}

.box-card {
  margin-top: 15px;
}
</style>
